package cn.kgc.javaweb.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author mosin
 * date 2022/2/12
 * @version 1.0
 * 德鲁伊连接池工具类的封装
 */
public final class DruidUtil {
   static DataSource dataSource = null;
    private DruidUtil(){}
    //初始化资源
    static{

        InputStream ins = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        try {
            properties.load(ins);
            //创建德鲁伊连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接池的方法
    public static DataSource getDataSource(){
        return dataSource;
    }


    //获取连接   从数据库连接池中获取
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
           return connection;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  connection;
    }

    //释放资源的方法
    public  static void closeAll(ResultSet rs, Statement stmt, Connection connection){
        try {
            if(rs!=null){  // 避免空指针
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if(stmt!=null){
                stmt.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        try {
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Connection connection = DruidUtil.getConnection();
        System.out.println("connection = " + connection);
    }
}
